<template>
  <el-dialog class="dialog" :model-value="visible" :show-close="false" width="40%" :z-index="9" top="5vh" :close-on-click-modal="false">
    <div class="closeimg" @click="cancel"><img src="@/assets/image/cf/img27.png" alt="" /></div>
    <div class="boardBox">
      <!-- 顶部信息栏 -->
      <!-- 主要内容区 -->
      <div class="formBoxcont">
        <div class="font20 color333 mb10 ml20">企业人力资源合规风险扫描仪</div>
        <div class="formBoxtou flex flex-align-center mt20">
          <div><img src="@/assets/image/cf/img26.png" alt="" /></div>
          <div class="flex flex-align-center flex-1">
            <div class="flex box-row-column ml20">
              <div class="font18 color333" v-if="loading">
                共发现
                <span class="colorff1200">{{ totalRiskCount }}</span>
                个风险点
              </div>

              <div class="font18 color333" v-else>
                扫描完成！ 共发现
                <span class="colorff1200">{{ totalRiskCount }}</span>
                个风险点，合规值为
                <span :class="totalScore > 70 ? 'colorff1200' : 'color2de07b'">{{ totalScore }}</span>
                分
              </div>
              <div class="flex mt10 fxzi1" v-if="!loading && totalScore == 0">
                <el-icon color="#01509f" style="margin-top: 2px; margin-left: 5px"><Warning /></el-icon>
                系统将于每月月初进行合规风险自动扫描
              </div>

              <div class="flex mt10 fxzi1" v-if="totalScore > 0">
                <el-icon color="#01509f" style="margin-top: 2px; margin-left: 5px"><Warning /></el-icon>
                {{ getScoreMessage(totalScore) }}
              </div>
            </div>
          </div>

          <div class="tou_close" v-if="loading" @click="cancel">取消扫描</div>
          <div class="tou_close" @click="cancel" v-else>关 闭</div>
        </div>
        <!-- 扫描状态 -->
        <!-- <div class="scan-status">
          <div class="status-content">
            <img class="logo" src="@/assets/image/cf/img26.png" alt="logo" />
            <div class="status-info">
              <div class="risk-count">
                共发现 <span class="highlight">{{ totalRiskCount }}</span> 个风险点
              </div>
              <div class="scanning" v-if="loading">
                <el-icon color="#01509f"><Loading /></el-icon>
                正在扫描：{{ currentScanningModule }}
              </div>
            </div>
            <div class="close-btn" @click="closeDialog">关 闭</div>
          </div>
        </div>v-if="loading" -->

        <!-- 扫描进度条 -->
        <div class="progress-container">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: `${currentProgress}%` }"></div>
          </div>
          <!-- <div class="progress-text">{{ currentProgress }}%</div>  -->
        </div>

        <!-- 分类展示 -->

        <div class="flex box-row-column mt20" style="padding: 0px 30px">
          <div class="flex box-row-column modules-grid" v-for="(modules, type) in categories" :key="type">
            <div class="category-header">
              <img :src="getCategoryIcon(type)" class="category-icon" />
              <div class="lizhi">{{ type }}</div>
              <div v-if="modules.length > 0" class="lizhi1">{{ "(" + modules.filter(m => m.loaded).length }}/{{ modules.length + ")" }}</div>
              <!-- <span class="risk-count">
            {{ getCategoryRiskCount(type) }}个风险点
          </span> -->
            </div>
            <div class="flex-container mt10">
              <div class="flex-item" v-for="module in modules" :key="module.id">
                <div><img :src="module.img" alt="" /></div>
                <div class="item-title">{{ module.name }}</div>
                <div class="item-saomiao" v-if="!module.loaded">
                  扫描中
                  <el-icon class="loading-icon"><Loading /></el-icon>
                </div>
                <div class="item-wufenxian" v-if="module.count == 0 && module.loaded">
                  <img src="@/assets/image/cf/imgdui.png" alt="" />
                  未扫出风险
                </div>

                <div class="item-saomiao" v-if="module.count > 0 && module.loaded">风险点:{{ module.count }}</div>
              </div>
              <!-- <div class="flex-item" >
                <div><img src="@/assets/image/cf/lizhixinzi.png" alt="" /></div>
                <div class="item-title">离职工资发放</div>

                <div class="item-saomiao">扫描中</div>
              </div> -->
            </div>
          </div>
        </div>

        <div class="categories" style="display: none">
          <div v-for="(modules, type) in categories" :key="type" class="category">
            <div class="category-header">
              <img :src="getCategoryIcon(type)" class="category-icon" />
              <h3>{{ type }}</h3>
              <span class="risk-count">{{ getCategoryRiskCount(type) }}个风险点</span>
            </div>

            <div class="modules-grid">
              <div v-for="module in modules" :key="module.id" class="module-card">
                <div class="module-image-container">
                  <img :src="module.img" :alt="module.name" class="module-image" />
                  <!-- 风险数加载状态 -->
                  <div class="risk-loading" v-if="!module.loaded">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                  </div>
                  <div class="risk-tag" v-else :class="module.count > 0 ? 'has-risk' : 'no-risk'">
                    {{ module.count > 0 ? `${module.count}个风险` : "无风险" }}
                  </div>
                </div>
                <div class="module-name">{{ module.name }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 总分展示 -->
        <div class="total-score" v-if="!loading" style="display: none">
          <el-divider />
          <div class="score-display">
            <span>合规总分：</span>
            <el-tag :type="getScoreTagType(totalScore)" size="large">{{ totalScore }}/100</el-tag>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from "vue";
  import { Loading, Warning } from "@element-plus/icons-vue";
  import { useCompanyDataStore } from "@/store/companys";
  import { SSEParser } from "@/utils/sseParser";
  import type { RiskModule } from "@/types/risk";

  interface EnhancedRiskModule extends RiskModule {
    loaded: boolean;
  }

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    companyid: {
      type: Number,
      default: null,
    },
  });

  const emit = defineEmits(["update:visible", "getnewdata"]);

  // 使用独立的dialogVisible控制显示
  const dialogVisible = ref(false);

  // 同步外部visible变化
  watch(
    () => props.visible,
    val => {
      dialogVisible.value = val;
      if (val) {
        loadRiskData();
        onCloseModal();
      }
    }
  );

  // 同步内部dialogVisible变化到外部
  watch(dialogVisible, val => {
    emit("update:visible", val);
  });
  function cancel() {
    onCloseModal();

    emit("update:visible", false);
    emit("getnewdata", "");
  }

  // 响应式数据
  const categories = ref<Record<string, EnhancedRiskModule[]>>({});
  const loading = ref(true);
  const currentProgress = ref(0);
  const currentScanningModule = ref("");
  const totalScore = ref(0);
  const companyDataStore = useCompanyDataStore();
  const companyId = ref(null);

  // 分数提示消息
  const getScoreMessage = score => {
    return score < 60 ? "警告！合规风险极高，请立即全面排查整改！" : score < 80 ? "当前企业合规情况不佳，请及时处理合规风险" : "当前企业合规情况良好，请保持并定期复查。";
  };
  // 计算总风险数
  const totalRiskCount = computed(() => {
    return Object.values(categories.value).reduce((total, modules) => {
      return total + modules.reduce((sum, module) => sum + module.count, 0);
    }, 0);
  });

  // 获取分类图标
  const getCategoryIcon = (type: string) => {
    const category = categories.value[type];
    return category && category.length > 0 ? category[0].x_img : "";
  };

  // 计算分类风险数
  const getCategoryRiskCount = (type: string) => {
    return categories.value[type]?.reduce((sum, module) => sum + module.count, 0) || 0;
  };

  // 分数标签类型
  const getScoreTagType = (score: number) => {
    return score >= 80 ? "success" : score >= 60 ? "warning" : "danger";
  };

  // 调用流式接口
  // const loadRiskData = async () => {
  //   try {
  //     resetState();
  //   let isCancelled = false; // 添加取消标志
  //     const response = await fetch(`https://demo-api.niuyuwang.com/hr/detection/risk_check?company_id=${props.companyid}`, {
  //       headers: { Accept: "text/event-stream" },
  //     });

  //     if (!response.ok) throw new Error("接口请求失败");
  //     if (!response.body) throw new Error("不支持流式数据");

  //     const reader = response.body.getReader();
  //     const decoder = new TextDecoder();

  //     while (true) {
  //             if (isCancelled) break; // 如果被取消，直接退出循环
  //       const { done, value } = await reader.read();
  //       if (done) break;

  //       const text = decoder.decode(value);
  //       const lines = text.split("\n").filter(line => line.trim() !== "");

  //       for (const line of lines) {
  //                 if (isCancelled) break; // 如果被取消，直接退出循环
  //         if (line.startsWith("data:")) {
  //           const data = JSON.parse(line.substring(5).trim());

  //           if (data.status === "starting") {
  //             // 彻底清空旧数据
  //             categories.value = {};
  //             currentProgress.value = 0;
  //           } else if (data.all_totle !== undefined) {
  //             totalScore.value = data.all_totle;
  //             loading.value = false;
  //           } else if (data.id !== undefined) {
  //             if (!categories.value[data.type]) {
  //               categories.value[data.type] = [];
  //             }

  //             // 清理旧模块（包括定时器）
  //             categories.value[data.type] = categories.value[data.type].filter(m => {
  //               if (m.id === data.id && m.cleanup) {
  //                 m.cleanup(); // 清理旧模块的定时器
  //                 return false; // 移除旧模块
  //               }
  //               return true;
  //             });

  //             // 添加新模块
  //             const moduleData = { ...data, loaded: false };
  //             categories.value[data.type].push(moduleData);

  //             // 设置延迟加载
  //             const timer = setTimeout(() => {
  //               moduleData.loaded = true;
  //             }, 500 + Math.random() * 1000);

  //             // 保存清理函数
  //             moduleData.cleanup = () => {
  //               clearTimeout(timer);
  //               moduleData.loaded = false; // 确保状态被重置
  //             };

  //             console.log("categories.value:", categories.value);
  //             currentProgress.value = data.progress;
  //             currentScanningModule.value = data.name;
  //           }
  //         }
  //       }

  //     }
  //   } catch (err) {
  //     if (!isCancelled) {
  //       console.error("扫描失败:", err);
  //       loading.value = false;
  //     }
  //   }

  //     // 返回一个清理函数
  //   return () => {
  //     isCancelled = true;
  //   };
  // };

  const loadRiskData = async () => {
    try {
      resetState();

      const response = await fetch(`https://demo-api.niuyuwang.com/hr/detection/risk_check?company_id=${props.companyid}`, { headers: { Accept: "text/event-stream" } });

      if (!response.ok) throw new Error("接口请求失败");
      if (!response.body) throw new Error("不支持流式数据");

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const text = decoder.decode(value);
        const lines = text.split("\n").filter(line => line.trim() !== "");

        for (const line of lines) {
          if (line.startsWith("data:")) {
            const data = JSON.parse(line.substring(5).trim());

            if (data.status === "starting") {
              categories.value = {};
              currentProgress.value = 0;
            } else if (data.all_totle !== undefined) {
              // 使用 all_totle 作为总分
              totalScore.value = data.all_totle;
              loading.value = false;
              // 扫描结束时，强制将所有模块的 loaded 状态设置为 false
              Object.values(categories.value).forEach(modules => {
                modules.forEach(module => {
                  module.loaded = true;
                });
              });
            } else if (data.id !== undefined) {
              if (!categories.value[data.type]) {
                categories.value[data.type] = [];
              }
              // 添加loaded字段，初始为false
              const moduleData = { ...data, loaded: false };
              categories.value[data.type].push(moduleData);
              currentProgress.value = data.progress;
              currentScanningModule.value = data.name;

              // 模拟延迟加载效果
              setTimeout(() => {
                moduleData.loaded = true;
              }, 500 + Math.random() * 1000);
            }
          }
        }
      }
    } catch (err) {
      console.error("扫描失败:", err);
      // 发生错误时，强制将所有模块的 loaded 状态设置为 false
      Object.values(categories.value).forEach(modules => {
        modules.forEach(module => {
          module.loaded = true;
        });
      });
      loading.value = false;
    }
  };

  // 重置状态
  const resetState = () => {
    console.log("重置所有状态...");
    Object.values(categories.value).forEach(modules => {
      modules.forEach(module => {
        if (module.cleanup) {
          console.log(`清理模块 ${module.id}，当前 loaded 状态: ${module.loaded}`);
          module.loaded = true;
          module.cleanup();
        }
      });
    });

    categories.value = {};
    currentProgress.value = 0;
    totalScore.value = 0;
    loading.value = true;
    currentScanningModule.value = "";
  };

  // 弹窗关闭时清理
  const onCloseModal = () => {
    console.log("弹窗关闭，强制清理所有模块...");
    Object.values(categories.value).forEach(modules => {
      modules.forEach(module => {
        if (module.cleanup) {
          console.log(`清理模块 ${module.id}，当前 loaded 状态: ${module.loaded}`);
          module.loaded = true;
          module.cleanup();
        }
      });
    });
    resetState();
  };
  const closeDialog = () => {
    dialogVisible.value = false;
    emit("chananniu", "");
  };
</script>
<style>
.dialog {
  background-color: rgba(255, 255, 255, 0);
  /* 完全透明 */
  box-shadow: none;
  /* 移除阴影 */
}
</style>
<style scoped lang="scss">
.closeimg {
  position: absolute;
  right: -12px;
  top: 60px;
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.boardBox {
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* 垂直居中 */

  /* 水平居中 */
  width: 100%;

  overflow: hidden;
  height: calc(100vh - 172px);

  &::-webkit-scrollbar {
    display: none;
  }

  -ms-overflow-style: none;
  scrollbar-width: none;

  .risk-loading {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 80px;
    height: 24px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;

    .loading-icon {
      animation: rotate 1.5s linear infinite;
    }
  }

  .tishi {
    font-size: 14px;
    color: #999;
    background-color: #f3f8fb;
    padding: 5px 10px;
    border-radius: 6px;
  }

  .formBoxtou {
    background-color: #f3f9ff;

    padding: 20px 50px;
  }

  .fxzi1 {
    color: #3090ff;
    background-color: #e0f1ff;
    font-size: 12px;
    border-radius: 5px;
    padding: 5px;
    flex: 1;
    /* 允许扩展和收缩 */
    min-width: 0;
    /* 关键：允许内容压缩 */
    overflow: hidden;
    /* 可选：超出隐藏 */
  }

  .tou_close {
    font-size: 15px;
    color: #01509f;
    border: solid 1px #01509f;
    border-radius: 50px;
    text-align: center;
    line-height: 30px;
    padding: 0px 20px;
    cursor: pointer;
  }

  .formBoxcont {
    padding: 20px 0px;
    background-color: #fff;

    border-radius: 10px;

    height: 100%;
    overflow: auto;
    margin-top: 30px;
    display: flex;
    flex-direction: column;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .fxzi2 {
    font-size: 15px;
    color: #666;
  }

  .lizhi {
    font-size: 17px;
    color: #333;
    font-weight: 500;
    // background: url("@/assets/image/cf/imglz.png") no-repeat left center;
    // background-size: 20px 20px;
    // padding-left: 25px;
  }

  .flex-container {
    display: flex;
    flex-wrap: wrap;
    /* 超出换行 */
    justify-content: flex-start;
    /* 左对齐 */
    gap: 10px;
    /* 子项间距 */
  }

  .flex-item {
    width: 20%;
    /* 固定宽度 */

    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    margin-bottom: 10px;
  }

  .item-title {
    margin-top: 8px;
    margin-bottom: 8px;
    font-size: 15px;
    color: #333;
  }

  .item-wufenxian1 {
    padding: 0px 10px;
    line-height: 25px;

    text-align: center;
  }

  .item-wufenxian {
    padding: 0px 10px;
    line-height: 25px;
    background-color: #dbffeb;
    text-align: center;
    border: solid 1px #1fbe7d;
    color: #1fbe7d;
    border-radius: 50px;
  }

  .item-saomiao {
    padding: 0px 20px;
    line-height: 25px;
    background-color: #fff4f4;
    text-align: center;
    border: solid 1px #ffb8b8;
    color: #666;
    border-radius: 50px;
    display: flex;
    align-items: center;
    justify-content: center;

    .loading-icon {
      animation: rotate 1.5s linear infinite;
      margin-left: 5px;
    }
  }

  .scan-status {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #01509f;
    font-size: 14px;
  }

  .progress-container {
    text-align: center;
  }

  .progress-bar {
    height: 5px;
    // background: repeating-linear-gradient(-45deg, rgb(73, 242, 186), rgb(73, 242, 186) 10px, rgb(0, 217, 144) 10px, rgb(0, 217, 144) 20px);

    overflow: hidden;
    margin-bottom: 10px;
  }

  .progress-fill {
    height: 100%;
    background: repeating-linear-gradient(-45deg, rgb(73, 242, 186), rgb(73, 242, 186) 10px, rgb(0, 217, 144) 10px, rgb(0, 217, 144) 20px);
    transition: width 0.3s ease;
  }

  .progress-text {
    font-size: 14px;
    color: #666;
  }

  .categories-container {
    margin-top: 20px;
  }

  .category-header {
    display: flex;
    align-items: center;
    padding-bottom: 10px;

    .category-icon {
      width: 24px;
      height: 24px;
      margin-right: 10px;
    }

    h3 {
      margin: 0;
      color: #333;
      font-size: 18px;
      flex-grow: 1;
    }

    .risk-count {
      font-size: 14px;
      color: #666;
    }
  }

  .modules-grid {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: solid 1px #eee;
  }
}

.risk-dialog {
  position: relative;
  background-color: white;
  border-radius: 8px;

  .dialog-container {
    height: 80vh;
    overflow: auto;
  }

  .header {
    background-color: #f3f9ff;
    padding: 20px;

    .header-content {
      display: flex;
      align-items: center;

      .logo {
        width: 40px;
        height: 40px;
      }

      .header-info {
        flex: 1;
        margin-left: 20px;

        .risk-count {
          font-size: 18px;
          color: #333;

          .highlight {
            color: #ff1200;
            font-weight: bold;
          }
        }

        .scan-info {
          display: flex;
          align-items: center;
          margin-top: 10px;
          color: #01509f;
          background-color: #f3f8fb;
          font-size: 12px;
          border-radius: 5px;
          padding: 5px;
        }
      }

      .close-btn {
        font-size: 15px;
        color: #01509f;
        border: 1px solid #01509f;
        border-radius: 50px;
        text-align: center;
        line-height: 30px;
        width: 70px;
        cursor: pointer;
      }
    }
  }

  .main-content {
    padding: 20px;

    .title {
      font-size: 20px;
      color: #333;
      margin-bottom: 10px;
    }

    .scan-status {
      background-color: #f3f9ff;
      padding: 20px;
      margin-top: 20px;

      .status-content {
        display: flex;
        align-items: center;

        .logo {
          width: 40px;
          height: 40px;
        }

        .status-info {
          flex: 1;
          margin-left: 20px;

          .scanning {
            display: flex;
            align-items: center;
            margin-top: 10px;
            font-size: 15px;
            color: #666;
          }
        }
      }
    }

    .progress-container {
      margin: 20px 0;
      text-align: center;

      .progress-bar {
        height: 10px;
        background: #f0f0f0;
        border-radius: 5px;
        overflow: hidden;
        margin-bottom: 10px;

        .progress-fill {
          height: 100%;
          background: #01509f;
          transition: width 0.3s ease;
        }
      }

      .progress-text {
        font-size: 14px;
        color: #666;
      }
    }

    .categories {
      margin-top: 20px;

      .category {
        margin-bottom: 30px;
        background: #fff;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

        .category-header {
          display: flex;
          align-items: center;
          margin-bottom: 15px;
          padding-bottom: 10px;
          border-bottom: 1px solid #eee;

          .category-icon {
            width: 24px;
            height: 24px;
            margin-right: 10px;
          }

          h3 {
            margin: 0;
            color: #333;
            font-size: 18px;
            flex-grow: 1;
          }

          .risk-count {
            font-size: 14px;
            color: #666;
          }
        }

        .modules-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
          gap: 15px;

          .module-card {
            background: #f9f9f9;
            border-radius: 6px;
            padding: 15px;
            transition: all 0.3s;
            text-align: center;

            &:hover {
              transform: translateY(-3px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            .module-image-container {
              position: relative;
              margin-bottom: 10px;
              min-height: 120px;

              .module-image {
                width: 100%;
                height: 120px;
                object-fit: contain;
                border-radius: 4px;
              }

              .risk-loading {
                position: absolute;
                bottom: 5px;
                right: 5px;
                width: 80px;
                height: 24px;
                background: rgba(255, 255, 255, 0.8);
                border-radius: 10px;
                display: flex;
                align-items: center;
                justify-content: center;

                .loading-icon {
                  animation: rotate 1.5s linear infinite;
                }
              }

              .risk-tag {
                position: absolute;
                bottom: 5px;
                right: 5px;
                padding: 2px 8px;
                border-radius: 10px;
                font-size: 12px;
                color: white;

                &.no-risk {
                  background: #1fbe7d;
                }

                &.has-risk {
                  background: #ff1200;
                }
              }
            }

            .module-name {
              font-size: 14px;
              color: #333;
            }
          }
        }
      }
    }

    .total-score {
      margin-top: 30px;
      text-align: center;

      .score-display {
        font-size: 18px;
        font-weight: bold;

        span {
          margin-right: 10px;
        }
      }
    }
  }
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}
</style>
